#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, request
from flask import render_template, jsonify, url_for
from sqlalchemy import create_engine

from db import Session
from db.models import get_model

app = Flask(__name__)
engine = create_engine('sqlite:///webapp.sqlite3', echo=False)
Session.configure(bind=engine)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/s/<keyword>/<table_id>')
def search(keyword, table_id):
    """
    return json format:
    {
        "status":0,
        "table": "12306cn",
        "head": ["account", "password"],
        "data": [
            ["aaaaa@qq.com", "12345678"],
            ["bbbbb@qq.com", "qwerty123"]
        ]
    }
    status: 0-success, 1-fail
    """
    ret = {}
    ret['status'] = 1
    UserTable = get_model(table_id)
    if not UserTable:
        return jsonify(ret)
    print(u'search table {} for {}'.format(
            UserTable.__tablename__, keyword))
    #from time import sleep
    #sleep(int(table_id)/9.0)
    #d = [
    #        ["0fatestar", "a6208536"],
    #        ["0xtest", "0xtest"],
    #        ["11340671@qq.com","testmyId"],
    #        ["11867test@78land.com","qq1234"],
    #    ]
    #ret['table'] = UserTable.__tablename__
    #ret['head'] = ['account', 'password']
    #ret['data'] = d
    session = Session()
    q = session.query(UserTable).filter(UserTable.account.like(
        '%{}%'.format(keyword))).limit(5)
    result = q.all()
    if not result:
        return jsonify(ret)
    ret['status'] = 0
    ret['table'] = UserTable.__tablename__
    ret['head'] = UserTable.__table__.columns.keys()[1:]
    ret['data'] = []
    for user in result:
        row = [getattr(user, col) for col in ret['head']]
        ret['data'].append(row)
    session.close()
    return jsonify(ret)

if __name__ == '__main__':
    app.run()
